<?
require 'global.php';
$sales_order=new DB(Tsales_order,$conn);
$sales_order_detail=new DB(Tsales_order_detail,$conn);
$address_book=new DB(Taddress_book,$conn);

// 电邮相关 email
include(ROOT."common/mail_send.php");
$email_template=new DB(Temail_template,$conn);
// cart
$cart=get_cart();
if(! $cart_qty) { header('location:./'); exit; }
//pre($cart); exit;

// order detail
$ref_no=date('YmdHis').rand(1000,9999);

// save ref_no in cookie for Paypal, 保存订单号到cookie, Paypal 会用到
setcookie('ref_no',encrypt($ref_no),time()+3600);
$order=$_POST;

// 验证数据来源是否合法
$ver=$order['key'];
if($ver != md5('ecomgear'.date('Ymd'))){ yell('请勿非法提交数据, 谢谢.','./'); exit; }

// 获取详细送货数据, get address book detail
$address_id=$order['address_book_id'];
if($address_id > 0) $arr_address=$address_book->get_row($address_id);

//pre($order); exit;
$arr=array(
	'currency_id'=>$order['currency_id'],
	'total_price'=>$order['total_price'],
	'order_price'=>$order['order_price'],
	'ref_no'=>$ref_no,
	'customer_id'=>$order['customer_id'],
	'email'=>$order['email'],
	'customer_remark'=>$order['customer_remark'],
	'invoice_header'=>$order['invoice_header'],
	'payment_method_id'=>$order['payment_method'],
	'shipment_cost'=>$order['shipment_cost'],
	'is_virtual'=>$order['is_virtual'],
	'with_tax'=>$order['with_tax'],
	//'with_deposit'=>$order['with_deposit'],
	'tax'=>$order['tax'],
	//'deposit'=>$order['deposit'],
);

// 收货信息
if($address_id > 0){
	$arr['country']=$arr_address['country_id'];
	$arr['province']=$arr_address['province_id'];
	$arr['city']=$arr_address['city_id'];
	$arr['county']=$arr_address['county_id'];
	$arr['address']=$arr_address['street'];
	$arr['zip']=$arr_address['zip'];
	$arr['contact_name']=$arr_address['contact_name'];
	$arr['mobile']=$arr_address['mobile'];
	$arr['phone']=$arr_address['phone'];
	$arr['shipment_method_id']=$order['shipment_method'];
}
else { // 订单全为虚拟商品, 联系信息取自客户资料
	$arr_i=$customer->get_row($order['customer_id']);
	$arr['contact_name']=$arr_i['first_name'].' '.$arr_i['last_name'];
	$arr['mobile']=$arr_i['mobile'];
	$arr['phone']=$arr_i['phone'];
}
//pre($arr); exit;

// 构造订单详细条目, 发电邮使用
$str_order='
<style>
.ordert { line-height:1.2; }
.ordert td { padding: 4px 6px; }
</style>
<table cellpadding="0" cellspacing="0" width="660" class="ordert" style="border-collapse:collapse;">
			<thead>
				<tr>
				<th style="border: 1px solid #888;">'.WEB_ITEM.'</th>
				<th style="border: 1px solid #888;">'.WEB_UNIT_PRICE.'</th>
				<th style="border: 1px solid #888;">'.WEB_PURCHASE_QUANTITY.'</th>
				</tr>
			</thead>
			<tbody>';
// 把订单写入数据库, 此处代码为事务
// 货币 currency
$tem_currency_code=$arrcurrency[$order['currency_id']]['code'];

try {
	$db->begin_transaction();
	$sales_order->insert($arr);
	$order_id=$sales_order->get_last_insert_id();
	//pre($order_id);
	// 获取产品价格
	$arr_product=array();
	$in_array=array();
	foreach($cart as $val) $in_array[]=$val['pid'];
	$where=array();
	$where[]=array('name'=>'id','val'=>$in_array,'opn'=>'in');
	$tem=$product->get_rows_advanced(1024,$where);
	foreach($tem as $val) $arr_product[$val['id']]=$val;

	$in_array=array();
	foreach($cart as $val) $in_array[]=$val['var'];
	// variation 子产品
	$where=array();
	$arr_var=array();
	$where[]=array('name'=>'id','val'=>$in_array,'opn'=>'in');
	$tem=$product_variation->get_rows_advanced(1024,$where);
	foreach($tem as $val) $arr_var[$val['id']]=$val;

 	// 写入订单详情, 此处未保存产品价格和折扣信息, 未完待续...
	foreach ($cart as $key => $val){
		$tem_product=$arr_product[$val['pid']];
		$tem_stock=$tem_product['stock'];
		$has_stock=$tem_stock>=$val['qty']?1:0;
		$unit_price=round($tem_product['price']*$currency_rate,2);
		if($val['var']>0){
			$tem_stock=$arr_var[$val['var']]['stock'];
			$has_stock=$tem_stock>=$val['qty']?1:0;
			$unit_price=round($arr_var[$val['var']]['price']*$currency_rate,2);
		}
		if($has_stock){
			$arr2=array(
				'sales_order_id'=>$order_id,
				'product_id'=>$val['pid'],
				'product_variation_id'=>$val['var'],
				'quantity'=>$val['qty'],
				'unit_price'=>$unit_price,
				);
			// 写入订单详情
			$sales_order_detail->insert($arr2);

			// 构造商品条目 - 电邮
			$tem_pic=$tem_product['small_pic'];
			$tem_link=$baseurl.'product-'.$tem_product['id'].'.html';
			$tem_name=str_cut($tem_product['name_'.$lang],PRODUCT_TITLE_DISPLAY_LENGTH,$lang);
			// variation
			$str_var='';
			if($val['var']){
				$tem_var=$product_variation->get_row($val['var']);
				$tem_price=round($tem_var['price']*$currency_rate,2); // var
				$tem_stock=$tem_var['stock'];  // var
				if($tem_var['size']) $str_var.=$option_label[2].': '.$option_value[$tem_var['size']].' &nbsp; ';
				if($tem_var['color']) $str_var.=$option_label[1].': '.$option_value[$tem_var['color']].' &nbsp; ';
				if($tem_var['other1']) $str_var.=$option_label[3].': '.$option_value[$tem_var['other1']].' &nbsp; ';
				if($tem_var['other2']) $str_var.=$option_label[4].': '.$option_value[$tem_var['other2']].' &nbsp; ';
			}
			$str_order.='<tr>
					<td style="border: 1px solid #888;width:300px;"><div><a style="float:left;" href="'.$tem_link.'" target="_blank"><img src="'.PRODUCT_PIC_HOST.$tem_pic.'"  width="60" style="padding: 0 8px 0 0;"  /></a><div class="name"><a href="'.$tem_link.'" target="_blank">'.$tem_name.'</a><br /><span style="color:#888">'.$str_var.'</span></div><div class="clear"></div></div></td>
					<td style="border: 1px solid #888;"><strong class="price red">'.$tem_currency_code.' '.$unit_price.'</strong></td>
					<td style="border: 1px solid #888;">'.$val['qty'].'</td>
					</tr>';
		}
	}
	
	// 减库存
	$product->reduce_stock_by_order($ref_no);
	$db->commit();
}
catch(PDOException $ex) {
	//Something went wrong rollback!
	$db->rollBack();
	//yell(WEB_ORDER_SUBMIT_FAIL,'./cart.html'); exit;
	echo $ex->getMessage();
	exit;
}

// 一切正常, 清空购物车
cart_clear();
$str_order.='<tbody></table>
<p>'.WEB_TOTAL_FOR_ITEMS.': '.$tem_currency_code.' '.$arr['order_price'].'<br />
'.WEB_SHIPMENT_FEE.': '.$tem_currency_code.' '.$arr['shipment_cost'].'<br />
'.WEB_ORDER_TOTAL.': '.$tem_currency_code.' '.$arr['total_price'].'</p>';

// 预览电邮
// echo $str_order;
// exit;

// 在线支付方式
// 1支付宝/2财付通/3payapl/4网银在线/5货到付款/6银行转账

// 前往支付页面
//echo 'Everything is OK, Payoff next - '.$order['payment_method'];
//echo '<br /> // 1支付宝/2财付通/3payapl/4网银在线/5货到付款/6银行转账';
$payment_method_id=$order['payment_method'];
$subject=WEB_ORDER.' - '.$ref_no.' - '.$config['SITE_COMPANY_'.LANG];
$body=$subject;
$pay_price = $order['total_price'];
//if($order['with_deposit']) $pay_price = $order['deposit'];

// 支付宝 Alipay 
if($payment_method_id==1){
	$action='api_alipay.php';
	require VIEW.'api_checkout.php';
	exit;
}
// Paypal
if($payment_method_id==3||$payment_method_id==7){
	$action='api_paypal.php';
	require VIEW.'api_checkout.php';
	exit;
}
// 货到付款 和 银行转账
if($payment_method_id==5 || $payment_method_id==6){
	// 发电邮 send email
	// 邮件变量 email variables
	$order_txt='<br />'; // 订单文本化, 用于发邮件, order in email
	$order_txt.=WEB_ORDER_REF_NO.': '.$ref_no.'<br />';
	//$order_txt.=WEB_TOTAL.': '.$tem_currency_code.$order['total_price'].'<br />';
	$order_txt.=$str_order;
	$order_txt.=WEB_ORDERED_TIME.': '.date('Y-m-d').'<br />';
	$var_email=array(
		'%nickname%'=>$customer_nickname,
		'%date%'=>date('Y-m-d'),
		'%datetime%'=>date('Y-m-d H:i:s'),
		'%url%'=>$baseurl,
		'%company%'=>$config['SITE_COMPANY_'.LANG],
		'%order%'=>$order_txt,
		'%order_ref_no%'=>$ref_no,
	);
	// replace vars 替换变量
	$arr_email = $email_template->get_row(3); // id=3 客户邮件
	$arr_email_admin = $email_template->get_row(4); // id=4 管理员邮件

	$subject=$arr_email['subject_'.$lang];
	$subject_admin=$arr_email_admin['subject_'.$lang];
	$body=$arr_email['content_'.$lang];
	$body_admin=$arr_email_admin['content_'.$lang];
	foreach ($var_email as $key => $value){
		$subject=str_replace($key, $value, $subject);
		$body=str_replace($key, $value, $body);
		$subject_admin=str_replace($key, $value, $subject_admin);
		$body_admin=str_replace($key, $value, $body_admin);
	}

	$body='<!doctype html><html>
	<head><meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
	<title>'.$subject.'</title></head>
	<body>'.$body.'</body></html>';
	$body_admin='<!doctype html><html>
	<head><meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
	<title>'.$subject_admin.'</title></head>
	<body>'.$body_admin.'</body></html>';
	$arr=array(
		'to'=>array($order['email']),
		'subject'=>$subject,
		'body'=>$body,
		'host'=>EMAIL_HOST,
		'account'=>EMAIL_ACCOUNT,
		'password'=>EMAIL_PASSWORD,
		'port'=>EMAIL_PORT,
		'name'=>EMAIL_NAME,
		'ssl'=>EMAIL_SSL,
	);
	//pre($arr);
	if(mail_send($arr)) $k=1; // 发信给顾客 send email to customer
	//exit;

	$email_admin_txt=DAILY_SALES_ORDER_RECIPIENT_EMAILS;
	$tem_array=explode(',', $email_admin_txt);
	$email_admin=array();
	foreach($tem_array as $val) $email_admin[]=trim($val);
	$arr_admin=array(
		'to'=>$email_admin,
		'subject'=>$subject_admin,
		'body'=>$body_admin,
		'host'=>EMAIL_HOST,
		'account'=>EMAIL_ACCOUNT,
		'password'=>EMAIL_PASSWORD,
		'port'=>EMAIL_PORT,
		'name'=>EMAIL_NAME,
		'ssl'=>EMAIL_SSL,
	);
	//pre($arr);
	if(mail_send($arr_admin)) $k=1; // 发信给管理员 send email to admin
	// email end
	if($payment_method_id==5){
		$message=array(
		'tip'=>WEB_ORDER_SUBMIT_COD,
		'links'=>array(array('name'=>WEB_MY_ORDER,'url'=>'myorder.html'),array('name'=>WEB_BACK_HOME,'url'=>'./')),
		'time'=>6.2,
		'url'=>'myorder.html',
		);
		require VIEW.'message.php';
		exit;
	}
	// 银行转账 
	if($payment_method_id==6){
		$message=array(
		'tip'=>WEB_ORDER_SUBMIT_BANK,
		'links'=>array(array('name'=>WEB_MY_ORDER,'url'=>'myorder.html'),array('name'=>WEB_BACK_HOME,'url'=>'./')),
		'time'=>6.2,
		'url'=>'myorder.html',
		);
		require VIEW.'message.php';
		exit;
	}
}
// SEO 设置 seo tags
$title=WEB_ORDER_SUBMIT.' - '.$config['SITE_COMPANY_'.LANG];
$kwd=$title;
$dpn=$kwd;

// view 加载视图
//require VIEW.'order.php';
// end of file
